//
//  WNRealmManager.swift
//  WalkNovel
//
//  Created by Kevin on 2023/7/4.
//

import UIKit
import RealmSwift
import Alamofire
import Realm

class WNRealmManager: NSObject {
    
    static let shared = WNRealmManager()
    
    var configSuc = false
    
    /// 配置数据库
    func configRealm() {
        // TODO: - ⚠️：如果要存储的数据模型属性发生变化,需要配置当前版本号比之前大
        let schemaVersion = UInt64(0)
        let dbPath = NSHomeDirectory().appending("/Documents/default.realm")
        let config = Realm.Configuration(fileURL: URL(string: dbPath), schemaVersion: schemaVersion, migrationBlock: { migration, oldSchemaVersion in
            if (oldSchemaVersion < schemaVersion) {
                
            }
        })
        Realm.Configuration.defaultConfiguration = config
        Realm.asyncOpen { result in
            switch result {
            case .success(_):
                WNRealmManager.shared.configSuc = true
            case .failure(_):
                WNRealmManager.shared.configSuc = false
            }
        }
    }
    
    /// 增
    func insertMessage(_ msg: ChayMsgModel) -> Void {
        if let realm = try? Realm(), WNRealmManager.shared.configSuc {
            try? realm.write {
                realm.add(msg)
            }
        }
    }
    
    /// 删
    func deleteMessage(_ msg: ChayMsgModel) {
        if let realm = try? Realm(), WNRealmManager.shared.configSuc {
            try? realm.write {
                realm.delete(msg)
            }
        }
    }
    
    /// 改
    func updatMessage( _ msg: ChayMsgModel) {
        if let realm = try? Realm(), WNRealmManager.shared.configSuc {
            try? realm.write {
                realm.add(msg, update: .all)
            }
        }
    }
    
    /// 查
    func queryMessage(_ msgId: String) -> ChayMsgModel? {
        if let realm = try? Realm(), WNRealmManager.shared.configSuc {
            return realm.objects(ChayMsgModel.self).filter({$0.msgId == msgId}).first
        }
        return nil
    }
    
    /// 查找所有
    func queryMessages() -> [ChayMsgModel]? {
        if let realm = try? Realm(), WNRealmManager.shared.configSuc {
            return realm.objects(ChayMsgModel.self).filter({$0.msgId != ""})
        }
        return nil
    }
    
    /// 删除所有
    func deleteMessages() {
        if let realm = try? Realm(), WNRealmManager.shared.configSuc {
            do {
                try realm.write {
                    realm.delete(realm.objects(ChayMsgModel.self))
                }
            }catch {}
        }
    }
}
